package hos.file.media;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;

import hos.file.provider.FileProviderX;
import hos.file.utils.FileUtils;

/**
 * <p>Title: MediaUtils </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2024-03-14 22:38
 */
public class MediaUri {
    //<editor-fold desc="CameraMedia">

    public static String createImageName() {
        return "JPEG_" + System.currentTimeMillis() + ".jpeg";
    }


    public static String createVideoName() {
        return "MP4_" + System.currentTimeMillis() + ".mp4";
    }


    public static String createAudioName() {
        return "AAC_" + System.currentTimeMillis() + ".aac";
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")

    public static Uri fileName2Uri(Context context, String fileName) {
        File path;
        FileType.Type fileType = FileType.getFileType(fileName);
        path = context.getExternalFilesDir("");
        if (path == null) {
            path = context.getFilesDir();
        }
        String filePath = path.getAbsolutePath() + File.separator
                + fileType.getDir() + File.separator + fileName;
        File file = new File(filePath);
        if (FileUtils.isFileExists(context, file)) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return FileProviderX.file2Uri(context, filePath);
    }


    public static Uri createImageUri(Context context, String imageFileName) {
        Uri imageUriNull = createImageUriNull(context, imageFileName);
        if (imageUriNull == null) {
            return fileName2Uri(context, imageFileName);
        }
        return imageUriNull;
    }


    public static Uri createVideoUri(Context context, String imageFileName) {
        Uri imageUriNull = createVideoUriNull(context, imageFileName);
        if (imageUriNull == null) {
            return fileName2Uri(context, imageFileName);
        }
        return imageUriNull;
    }


    public static Uri createAudioUri(Context context, String imageFileName) {
        Uri imageUriNull = createAudioUriNull(context, imageFileName);
        if (imageUriNull == null) {
            return fileName2Uri(context, imageFileName);
        }
        return imageUriNull;
    }


    public static Uri createImageUriNull(Context context, String imageFileName) {
        ContentResolver resolver = context.getContentResolver();
        if (resolver == null) {
            return null;
        }
        ContentValues contentValues = new ContentValues();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        }
        contentValues.put(MediaStore.MediaColumns.TITLE, imageFileName);
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, imageFileName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        try {
            return resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        } catch (Exception e) {
            return null;
        }
    }


    public static Uri createVideoUriNull(Context context, String imageFileName) {
        ContentResolver resolver = context.getContentResolver();
        if (resolver == null) {
            return null;
        }
        ContentValues contentValues = new ContentValues();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES);
        }
        contentValues.put(MediaStore.MediaColumns.TITLE, imageFileName);
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, imageFileName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
        try {
            return resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
        } catch (Exception e) {
            return null;
        }
    }


    public static Uri createAudioUriNull(Context context, String imageFileName) {
        ContentResolver resolver = context.getContentResolver();
        if (resolver == null) {
            return null;
        }
        ContentValues contentValues = new ContentValues();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentValues.put(MediaStore.Audio.Media.RELATIVE_PATH, Environment.DIRECTORY_MUSIC);
        }
        contentValues.put(MediaStore.MediaColumns.TITLE, imageFileName);
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, imageFileName);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/aac");
        try {
            return resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, contentValues);
        } catch (Exception e) {
            return null;
        }
    }

    //</editor-fold>

    /**
     * 更新系统相册
     */
    public static void updateSystemPhotoAlbum(Context context, final String path) {
        File file = FileUtils.getFileByPath(path);
        if (!FileUtils.isFileExists(context, file)) {
            // 文件不存在
            return;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            final Intent intent;
            if (file.isDirectory()) {
                intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
                intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
                intent.setData(Uri.fromFile(file));
            } else {
                intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(Uri.fromFile(file));
            }
            context.sendBroadcast(intent);
            return;
        }
        ContentResolver resolver = context.getContentResolver();
        Uri uri = null;
        if (FileType.isIMAGE(path)) {
            uri = createImageUriNull(context, file.getName());
        } else if (FileType.isAUDIO(path)) {
            uri = createAudioUriNull(context, file.getName());
        } else if (FileType.isVIDEO(path)) {
            uri = createVideoUriNull(context, file.getName());
        }
        if (uri != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
                context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
            writeToUri(file, resolver, uri);
        }
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
    }

    /**
     * 将文件填充到URI
     */
    private static void writeToUri(File file, ContentResolver resolver, Uri image) {
        //拷贝文件到相册的uri,android11及以上得这么干，否则不会显示。可以参考ScreenMediaRecorder的save方法
        OutputStream os = null;
        InputStream is = null;
        try {
            os = resolver.openOutputStream(image, "w");
            if (os == null) {
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Files.copy(file.toPath(), os);
            } else {
                final int sBufferSize = 524288;
                is = new BufferedInputStream(new FileInputStream(file), sBufferSize);
                byte[] data = new byte[sBufferSize];
                for (int len; (len = is.read(data)) != -1; ) {
                    os.write(data, 0, len);
                }
            }
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
